package com.iqilu.ksd.activity;

import android.Manifest;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.iqilu.ksd.R;
import com.iqilu.ksd.activity.live.PhotoActivity;
import com.iqilu.ksd.bean.PaikeBean;
import com.iqilu.ksd.bean.PictureBean;
import com.iqilu.ksd.constant.Api;
import com.iqilu.ksd.constant.Config;
import com.iqilu.ksd.constant.ImageSize;
import com.iqilu.ksd.event.CityChangeEvent;
import com.iqilu.ksd.utils.BaseUtils;
import com.iqilu.ksd.utils.CacheUtils;
import com.iqilu.ksd.utils.FileUtils;
import com.iqilu.ksd.utils.ImageUtils;
import com.iqilu.ksd.utils.JSONUtils;
import com.iqilu.ksd.utils.SPUtils;
import com.iqilu.ksd.widget.LigDialog;
import com.jaeger.library.StatusBarUtil;
import com.muzhi.camerasdk.model.CameraSdkParameterInfo;
import com.muzhi.camerasdk.model.ImageInfo;
import com.zhy.http.okhttp.OkHttpUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import id.zelory.compressor.Compressor;
import okhttp3.Response;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;

/**
 * Created by Coofee on 2016/11/2.
 */

public class AddPaikeActivity extends BaseActivity implements View.OnClickListener, EasyPermissions.PermissionCallbacks {

    private static final String TAG = "AddPaikeActivity";

    private String city;
    private ArrayList<ImageInfo> albumlist;
    private PaikeBean mData = new PaikeBean();
    private String picPath;
    private MyAdapter adapter;
    private String picList[] = new String[3];
    private CameraSdkParameterInfo mCameraSdkParameterInfo = new CameraSdkParameterInfo();

    private LigDialog ligDialog;
    private ImageView btLeft;
    private ImageView btRight;
    private TextView tvTitle;
    private EditText etNickname;
    private ImageView imgLocation;
    private TextView tvLocation;
    private EditText etPhone;
    private EditText etBody;
    private ImageView btPhoto;
    private ImageView btAlbum;
    private GridView gvList;
    private Button btSubmit;

    private static final int PER_STORAGE = 1001;
    private static final int PER_CAMERA = 1002;
    private static final int CODE_PHOTO = 1003;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_addpaike);
        StatusBarUtil.setColor(this, ContextCompat.getColor(this, R.color.blue_dark), Config.STATUSBAR_ALPHA);
        initView();
        initCity();
    }

    private void initView() {
        btLeft = getView(R.id.bt_left);
        btRight = getView(R.id.bt_right);
        tvTitle = getView(R.id.tv_title);
        setZHTypeface(tvTitle);
        etNickname = getView(R.id.et_nickname);
        imgLocation = getView(R.id.img_location);
        tvLocation = getView(R.id.tv_location);
        etPhone = getView(R.id.et_phone);
        etBody = getView(R.id.et_body);
        btPhoto = getView(R.id.bt_photo);
        btAlbum = getView(R.id.bt_album);
        gvList = getView(R.id.gv_list);
        btSubmit = getView(R.id.bt_submit);
        tvTitle.setText(getString(R.string.pk_title));
        btLeft.setOnClickListener(this);
        btRight.setImageResource(R.drawable.bt_add_paike_submit);
        imgLocation.setOnClickListener(this);
        btAlbum.setOnClickListener(this);
        btPhoto.setOnClickListener(this);
        btSubmit.setOnClickListener(this);

    }

    @AfterPermissionGranted(PER_STORAGE)
    private void selectFromAlbum() {
        Log.i(TAG, "selectFromAlbum");
        String perm = Manifest.permission.READ_EXTERNAL_STORAGE;
        if (EasyPermissions.hasPermissions(this, perm)) {
            if (getSize() >= picList.length) {
                Toast.makeText(this, R.string.pk_select_album_max, Toast.LENGTH_SHORT).show();
                return;
            }
            initAlbumConfig(picList.length - getSize());
            Intent intent = new Intent();
            intent.setClassName(getApplication(), "com.muzhi.camerasdk.PhotoPickActivity");
            Bundle b = new Bundle();
            b.putSerializable(CameraSdkParameterInfo.EXTRA_PARAMETER, mCameraSdkParameterInfo);
            intent.putExtras(b);
            startActivityForResult(intent, CameraSdkParameterInfo.TAKE_PICTURE_FROM_GALLERY);
        } else {
            EasyPermissions.requestPermissions(this, getString(R.string.per_con_storage), PER_STORAGE, perm);
        }
    }

    @AfterPermissionGranted(PER_CAMERA)
    private void takePhoto() {
        String perm = Manifest.permission.CAMERA;
        if (EasyPermissions.hasPermissions(this, perm)) {
            if (getSize() >= picList.length) {
                Toast.makeText(this, R.string.pk_select_album_max, Toast.LENGTH_SHORT).show();
                return;
            }
            String state = Environment.getExternalStorageState();
            if (state.equals(Environment.MEDIA_MOUNTED)) {
                Intent getImageByCamera = new Intent("android.media.action.IMAGE_CAPTURE");
                String path = CacheUtils.getCacheDir(this);
                picPath = path + System.currentTimeMillis() + ".jpg";
                getImageByCamera.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(picPath)));
                getImageByCamera.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
                startActivityForResult(getImageByCamera, CODE_PHOTO);
            } else {
                Toast.makeText(this, R.string.pk_no_sd, Toast.LENGTH_LONG).show();
            }
        } else {
            EasyPermissions.requestPermissions(this, getString(R.string.per_con_camera), PER_CAMERA, perm);
        }
    }

    private int getSize() {
        int j = 0;
        for (int i = 0; i < picList.length; i++) {
            if (!TextUtils.isEmpty(picList[i])) {
                j++;
            } else {
                break;
            }
        }
        return j;
    }

    private void save() {
        if (TextUtils.isEmpty(etNickname.getText().toString())) {
            Toast.makeText(this, R.string.pk_nickname_empty, Toast.LENGTH_SHORT).show();
            return;
        }
        if (!BaseUtils.matchPhone(etPhone.getText().toString())) {
            Toast.makeText(this, R.string.pk_phone_error, Toast.LENGTH_SHORT).show();
            return;
        }
        if (TextUtils.isEmpty(etBody.getText().toString())) {
            Toast.makeText(this, R.string.pk_body_empty, Toast.LENGTH_SHORT).show();
            return;
        }
        new SubmitData().execute();
    }

    private void initAlbumConfig(int num) {
        mCameraSdkParameterInfo.setSingle_mode(false);
        mCameraSdkParameterInfo.setShow_camera(false);
        mCameraSdkParameterInfo.setCroper_image(false);
        mCameraSdkParameterInfo.setFilter_image(false);
        mCameraSdkParameterInfo.setMax_image(num);
    }

    private void initCity() {
        city = SPUtils.getPref(this, Config.CITY, getString(R.string.default_city));
        city = String.format(getResources().getString(R.string.pk_location), city);
        tvLocation.setText(city);
    }

    private class MyAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return picList == null ? 0 : picList.length;
        }

        @Override
        public Object getItem(int i) {
            return picList[i];
        }

        @Override
        public long getItemId(int i) {
            return i;
        }

        @Override
        public View getView(final int i, View view, ViewGroup viewGroup) {
            ViewHolder holder;
            if (view == null) {
                holder = new ViewHolder();
                view = LayoutInflater.from(AddPaikeActivity.this).inflate(R.layout.list_item_pic_paike, null);
                holder.imgThumb = (ImageView) view.findViewById(R.id.img_thumb);
                holder.imgDel = (ImageView) view.findViewById(R.id.img_del);
                holder.btSelect = (CheckBox) view.findViewById(R.id.bt_select);
                view.setTag(holder);
            } else {
                holder = (ViewHolder) view.getTag();
            }
            holder.imgDel.setVisibility(View.VISIBLE);
            holder.btSelect.setVisibility(View.GONE);
            holder.imgThumb.setImageURI(Uri.parse("file://" + picList[i]));
            holder.imgDel.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    picList[i] = "";
                    String newPics[] = new String[4];
                    int i = 0;
                    for (int j = 0; j < picList.length; j++) {
                        if (!TextUtils.isEmpty(picList[j])) {
                            newPics[i] = picList[j];
                            i++;
                        }
                    }
                    picList = newPics;
                    adapter.notifyDataSetChanged();
                }
            });
            return view;
        }

        class ViewHolder {
            ImageView imgThumb;
            ImageView imgDel;
            CheckBox btSelect;
        }
    }

    // 提交爆料信息
    class SubmitData extends AsyncTask<Void, Void, Void> {

        int result = 0;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            ligDialog = new LigDialog(AddPaikeActivity.this, getString(R.string.waiting));
            ligDialog.show();
            mData.setNickname(etNickname.getText().toString());
            mData.setLocation(tvLocation.getText().toString());
            mData.setPhone(etPhone.getText().toString());
            mData.setBody(etBody.getText().toString());
        }

        @Override
        protected Void doInBackground(Void... voids) {
            Response response = null;
            String url = Api.URL_CLUE;
            Map<String, File> files = new HashMap<>();
            for (int i = 0; i < picList.length; i++) {
                if(TextUtils.isEmpty(picList[i])) continue;
                File file = new File(picList[i]);
                files.put(file.getName(), file);
            }
            try {
                response = OkHttpUtils
                        .post()
                        .url(url)
                        .addParams("nickname", "" + mData.getNickname())
                        .addParams("location", "" + mData.getLocation())
                        .addParams("phone", "" + mData.getPhone())
                        .addParams("body", "" + mData.getBody())
                        .files("filedata[]", files)
                        .tag(this)
                        .build()
                        .execute();
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (response != null) {
                try {
                    result = JSONUtils.filterInt(response.body().string(), "status", 0);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
            ligDialog.dismiss();
            if (result == 0) {
                Toast.makeText(AddPaikeActivity.this, R.string.pk_add_error, Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(AddPaikeActivity.this, R.string.pk_add_success, Toast.LENGTH_SHORT).show();
                finish();
            }
        }

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.bt_left:
                finish();
                break;
            case R.id.img_location:
                startActivity(new Intent(AddPaikeActivity.this, CityActivity.class));
                break;
            case R.id.bt_submit:
                save();
                break;
            case R.id.bt_photo:
                takePhoto();
                break;
            case R.id.bt_album:
                selectFromAlbum();
                break;
            default:
                break;
        }
    }

    class CompressThread extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            ligDialog = new LigDialog(AddPaikeActivity.this, getString(R.string.waiting));
            ligDialog.show();
        }

        @Override
        protected Void doInBackground(Void... params) {
            for (int i = 0; i < picList.length; i++) {
                if (TextUtils.isEmpty(picList[i]) || picList[i].contains("compress")) continue;
                File compressedImage = new Compressor.Builder(AddPaikeActivity.this)
                        .setMaxWidth(ImageSize.BIG_WIDTH)
                        .setMaxHeight(ImageSize.BIG_HEIGHT)
                        .setQuality(90)
                        .setCompressFormat(Bitmap.CompressFormat.JPEG)
                        .setDestinationDirectoryPath(CacheUtils.getCompressDir(AddPaikeActivity.this))
                        .build()
                        .compressToFile(new File(picList[i]));
                picList[i] = compressedImage.getPath();
                compressedImage = null;
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
            ligDialog.dismiss();
            if (adapter == null) {
                adapter = new MyAdapter();
                gvList.setAdapter(adapter);
            }
            adapter.notifyDataSetChanged();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        PictureBean pictureBean;
        if (requestCode == CameraSdkParameterInfo.TAKE_PICTURE_FROM_GALLERY) {
            if (data == null) return;
            mCameraSdkParameterInfo = (CameraSdkParameterInfo) data.getExtras().getSerializable(CameraSdkParameterInfo.EXTRA_PARAMETER);
            ArrayList<String> list = mCameraSdkParameterInfo.getImage_list();
            if (list == null || list.size() == 0) return;
            int j = 0;
            for (int i = 0; i < picList.length; i++) {
                if (TextUtils.isEmpty(picList[i]) && j < list.size()) {
                    picList[i] = list.get(j);
                    j++;
                }
            }
        }
        if (requestCode == CODE_PHOTO) {
            if (!FileUtils.isFileExists(picPath)) {
                return;
            }
            for (int i = 0; i < picList.length; i++) {
                if (TextUtils.isEmpty(picList[i])) {
                    picList[i] = picPath;
                    break;
                }
            }
        }
        new CompressThread().execute();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {

    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            new AppSettingsDialog.Builder(this, getString(R.string.per_con_camera_storage))
                    .setTitle(getString(R.string.per_title))
                    .setPositiveButton(getString(R.string.setting))
                    .setNegativeButton(getString(R.string.cancel), null)
                    .setRequestCode(requestCode)
                    .build()
                    .show();
        }
    }

    @Subscribe(threadMode = ThreadMode.POSTING)
    public void onMessageEvent(CityChangeEvent event) {
        initCity();
    }

    @Override
    public void onStart() {
        super.onStart();
        EventBus.getDefault().register(this);
    }

    @Override
    public void onStop() {
        super.onStop();
        EventBus.getDefault().unregister(this);
    }
}
